package com.project.systemfront.controller;


import com.project.systemfront.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/common")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Value("${upload.profile}")
    private String uploadPath;

    private static final String FILE_DELIMETER = ",";

    @PostMapping("/upload")
    public Result uploadFiles(@RequestParam("files") MultipartFile[] files) {
        if (files.length == 0) {
            return Result.error(500, "No files were uploaded.");
        }

        List<String> fileUrls = new ArrayList<>();

        try {
            // 获取当前日期时间并格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = sdf.format(new Date());

            // 创建目录结构
            String dirPath = uploadPath + "/upload/" + datePath;
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue; // 跳过空文件
                }

                // 生成新的文件名
                String originalFilename = file.getOriginalFilename();
                String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String uniqueFileName = "R-C_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().substring(0, 4).toUpperCase() + fileExtension;

                // 完整的文件路径
                String filePath = dirPath + "/" + uniqueFileName;

                // 保存文件到服务器
                file.transferTo(new File(filePath));

                // 收集文件访问路径
                fileUrls.add("/profile/upload/" + datePath + "/" + uniqueFileName);
            }

            // 返回所有文件访问路径
            return Result.success(String.join(FILE_DELIMETER, fileUrls));
        } catch (IOException e) {
            log.error("Failed to upload files: {}", e.getMessage());
            return Result.error(500, "Failed to upload files: " + e.getMessage());
        }
    }
}